using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;


namespace Assignment1
{
    public enum Direction
    {
        LEFT,
        RIGHT,
        UP,
        DOWN
    }
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        Texture2D circleTexture;
        SpriteFont font;

        LoadMap loadMap;
        
        private int squareValue;
        private float roadRadius;

        List<PathFinderNode> solution;
        
        private float velocityLength;
        
        Vector2 predictivePos;
        int currentPreNodePos = 1;
        Direction currentPreDirection;

        Vector2 playerVelocity;
        Vector2 playerPos;
        Vector2 playerFuturePos;

        public Game1(string fileName)
        {
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            graphics.PreferredBackBufferHeight = 800;
            graphics.PreferredBackBufferWidth = 800;
            this.IsMouseVisible = true;
            loadMap = new LoadMap(fileName);
        }

        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            
            circleTexture = Content.Load<Texture2D>("circle");
            font = Content.Load<SpriteFont>("font");

            squareValue = (int)(800 / Math.Max(LoadMap.globalMap.MaxHeight, LoadMap.globalMap.MaxWidth));
            roadRadius = squareValue / 2;
            velocityLength = squareValue * 0.05f;

            //Initialize path using new AStar
            //////////////////////////////////////////////////////////////////////////
            //////////////////////////////////////////////////////////////////////////
            PathFinder finder = new PathFinder(LoadMap.globalMap.MapData);
            System.Drawing.Point start = new System.Drawing.Point(LoadMap.globalMap.StartPos.x, LoadMap.globalMap.StartPos.y);
            System.Drawing.Point goal = new System.Drawing.Point(LoadMap.globalMap.GoalSpot.x, LoadMap.globalMap.GoalSpot.y);

            finder.Diagonals = false;
            solution = finder.FindPath(start, goal);

            //if found solution, traverse to set path ad player position
            if (solution != null)
            {
                foreach (PathFinderNode node in solution)
                {
                    LoadMap.globalMap.setMap(node.X, node.Y, BlockType.PATH);
                }
                predictivePos = new Vector2(solution[currentPreNodePos].X, solution[currentPreNodePos].Y);
                playerPos = new Vector2(solution[currentPreNodePos].PX, solution[currentPreNodePos].PY);
                playerVelocity = predictivePos - playerPos;
                playerVelocity.Normalize();
                playerVelocity *= (velocityLength * 0.94f);
            }
            //////////////////////////////////////////////////////////////////////////


            base.Initialize();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);

            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed || Keyboard.GetState().IsKeyDown(Keys.Escape))
                this.Exit();

            //Kinematic movement follows path.
            KinematicMovement(gameTime);

            //Steering movement seeking kinematic movement
            playerFuturePos = playerPos + playerVelocity * 0.2f;
            if (Vector2.Distance(playerFuturePos, predictivePos) > 0.1f)
            {
                Seek();
            }

            playerPos += playerVelocity * (float)(gameTime.ElapsedGameTime.TotalSeconds);
            // TODO: Add your update logic here

            base.Update(gameTime);
        }

        //Seek steering behavior
        private void Seek()
        {
            playerVelocity = predictivePos - playerPos;
            playerVelocity.Normalize();
            playerVelocity *= (velocityLength * 0.94f);
        }

        //Kinematic movement follows path.
        private void KinematicMovement(GameTime gameTime)
        {
            if (solution != null)
            {
                if (currentPreNodePos < solution.Count - 1)
                {
                    if (solution[currentPreNodePos + 1].X > solution[currentPreNodePos].X)
                        currentPreDirection = Direction.RIGHT;
                    if (solution[currentPreNodePos + 1].X < solution[currentPreNodePos].X)
                        currentPreDirection = Direction.LEFT;
                    if (solution[currentPreNodePos + 1].Y > solution[currentPreNodePos].Y)
                        currentPreDirection = Direction.DOWN;
                    if (solution[currentPreNodePos + 1].Y < solution[currentPreNodePos].Y)
                        currentPreDirection = Direction.UP;

                    switch (currentPreDirection)
                    {
                        case Direction.RIGHT:
                            predictivePos.X += (float)(velocityLength * gameTime.ElapsedGameTime.TotalSeconds);
                            if (predictivePos.X > solution[currentPreNodePos + 1].X) currentPreNodePos++;
                            break;
                        case Direction.LEFT:
                            predictivePos.X -= (float)(velocityLength * gameTime.ElapsedGameTime.TotalSeconds);
                            if (predictivePos.X < solution[currentPreNodePos + 1].X) currentPreNodePos++;
                            break;
                        case Direction.DOWN:
                            predictivePos.Y += (float)(velocityLength * gameTime.ElapsedGameTime.TotalSeconds);
                            if (predictivePos.Y > solution[currentPreNodePos + 1].Y) currentPreNodePos++;
                            break;
                        case Direction.UP:
                            predictivePos.Y -= (float)(velocityLength * gameTime.ElapsedGameTime.TotalSeconds);
                            if (predictivePos.Y < solution[currentPreNodePos + 1].Y) currentPreNodePos++;
                            break;
                    }
                }
            }
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            GraphicsDevice.Clear(Color.CornflowerBlue);

            // TODO: Add your drawing code here
            spriteBatch.Begin();
            if (solution != null)
            {
                int y = 0;
                foreach (List<BlockType> row in LoadMap.globalMap.MapData)
                {
                    int x = 0;
                    foreach (BlockType columm in row)
                    {
                        switch (columm)
                        {
                            case BlockType.WALL:
                                spriteBatch.Draw(CreateRectangle(squareValue, squareValue, Color.Black), new Vector2(x * squareValue, y * squareValue), Color.White);
                                break;
                            case BlockType.TERRAIN:
                                spriteBatch.Draw(CreateRectangle(squareValue, squareValue, Color.LimeGreen), new Vector2(x * squareValue, y * squareValue), Color.White);
                                break;
                            case BlockType.GOAL:
                                spriteBatch.Draw(CreateRectangle(squareValue, squareValue, Color.Red), new Vector2(x * squareValue, y * squareValue), Color.White);
                                break;
                            case BlockType.START:
                                spriteBatch.Draw(CreateRectangle(squareValue, squareValue, Color.Blue), new Vector2(x * squareValue, y * squareValue), Color.White);
                                break;
                            case BlockType.VISITED:
                                spriteBatch.Draw(CreateRectangle(squareValue, squareValue, Color.WhiteSmoke), new Vector2(x * squareValue, y * squareValue), Color.White);
                                break;
                            case BlockType.PATH:
                                spriteBatch.Draw(CreateRectangle(squareValue, squareValue, Color.White), new Vector2(x * squareValue, y * squareValue), Color.White);
                                break;
                        }
                        x++;
                    }
                    y++;
                }
                spriteBatch.Draw(circleTexture, predictivePos * squareValue + new Vector2(squareValue / 2, squareValue / 2), null, Color.White, 0, new Vector2(24, 24), 0.15f, SpriteEffects.None, 0);
                spriteBatch.Draw(circleTexture, playerPos * squareValue + new Vector2(squareValue / 2, squareValue / 2), null, Color.Black, 0, new Vector2(24, 24), 0.15f, SpriteEffects.None, 0);
                spriteBatch.Draw(circleTexture, playerFuturePos * squareValue + new Vector2(squareValue / 2, squareValue / 2), null, Color.White*0.5f, 0, new Vector2(24, 24), 0.15f, SpriteEffects.None, 0);

                foreach (PathFinderNode node in solution)
                {

                }
            }
            else
            {
                spriteBatch.Draw(CreateRectangle(800, 800, Color.White), Vector2.Zero, Color.White);
                spriteBatch.DrawString(font, "Sorry no solution for this map", Vector2.Zero, Color.Black);
            }

            spriteBatch.End();

            base.Draw(gameTime);
        }

        public Texture2D CreateRectangle(int width, int height, Color recColor)
        {
            // create the rectangle texture, ,but it will have no color! lets fix that
            Texture2D rectangleTexture = new Texture2D(GraphicsDevice, width, height, false, SurfaceFormat.Color);

            // set the color to the amount of pixels
            Color[] color = new Color[width * height];

            // loop through all the colors setting them to whatever values we want
            for (int i = 0; i < color.Length; i++)
            {
                color[i] = recColor;
            }

            // set the color data on the texture
            rectangleTexture.SetData(color);
            return rectangleTexture;
        }
    }
}
